package servlet.aiface;

import commons.baseServlet.BaseServlet;
import commons.r.R;
import service.AIFaceService;
import service.impl.AIFaceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * servlet.aiface
 * User: 邱
 * Date: 2024/12/21 16:14
 * Description:
 * Version: V1.0
 */
@WebServlet("/aiface/*")
@MultipartConfig
public class AIFaceServlet extends BaseServlet {
    AIFaceService aiFaceService = new AIFaceServiceImpl();

    /**
     * 人脸注册
     * @param request
     * @return
     */
    public R faceRegister(HttpServletRequest request){
        StringBuffer image = getImage(request);
        String userInfo = request.getParameter("userInfo");
        String phoneNum = request.getParameter("phoneNum");

        String str = aiFaceService.faceRegister(image, userInfo, phoneNum);
        return R.ok(str);
    }

    /**
     * 人脸搜索
     * @param request
     * @return
     */
    public R faceLogin(HttpServletRequest request) {
        StringBuffer image = getImage(request);

        String userInfo = aiFaceService.faceLogin(image);
        return R.ok().addData("userInfo", userInfo);
    }

    /**
     * 获得图片的base64格式的stringBuffer
     * @param request
     * @return
     */
    public StringBuffer getImage(HttpServletRequest request){
        Part file = null;
        StringBuffer image = new StringBuffer();
        BufferedReader reader = null;
        try {
            file = request.getPart("file");
            InputStream inputStream = file.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine())!= null) {
                image.append(line);
            }
            return image;
        } catch (IOException | ServletException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader!= null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
